import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:game2048/digital_evolution/game_page.dart';
import 'package:game2048/main.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LevelSelectionPage extends StatefulWidget {
  const LevelSelectionPage({Key? key}) : super(key: key);

  @override
  _LevelSelectionPageState createState() => _LevelSelectionPageState();
}

class _LevelSelectionPageState extends State<LevelSelectionPage> {
  int currentLevel = 0;
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _fetchCurrentLevel();
  }

  Future<void> _fetchCurrentLevel() async {
    try {
      // 使用 GameService 获取当前关卡
      final int? level = await GameService.getLevel();
      if (level != null) {
        currentLevel = level;
      }
      setState(() {
        isLoading = false;
      });
    } catch (e) {
      // 处理错误
      print('获取当前关卡时出错: $e');
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return Scaffold(
        body: Center(
          child: CircularProgressIndicator(),
        ),
      );
    }

    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        title: Text('selectLevel'.tr()),
        backgroundColor: Colors.transparent,
        elevation: 0,
      ),
      body: Stack(
        children: [
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            top: 0,
            child: Image.asset("assets/bg.png", fit: BoxFit.cover),
          ),
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(5, (index) {
                return LevelButton(
                  index: index + 1,
                  // 简化逻辑
                  enabled: currentLevel >= index,
                  onPressed: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) =>
                            ReusableGamePage(checkPointNum: index + 1),
                      ),
                    ).then((_) {
                      _fetchCurrentLevel();
                      setState(() {
                        
                      });
                    });
                  },
                );
              }),
            ),
          ),
        ],
      ),
    );
  }
}

class LevelButton extends StatelessWidget {
  final int index;
  final bool enabled;
  final VoidCallback? onPressed;

  const LevelButton({
    Key? key,
    required this.index,
    required this.enabled,
    this.onPressed,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: enabled ? onPressed : null,
      child: Container(
        padding: EdgeInsets.all(16.0),
        decoration: BoxDecoration(
          color: enabled
              ? Colors.white
              : Colors.grey.withOpacity(0.5), // 灰色背景表示不可点击
          borderRadius: BorderRadius.circular(8.0),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.5),
              offset: Offset(0, 2),
              blurRadius: 4,
            ),
          ],
        ),
        child: Center(
          child: Text('level'.tr() + index.toString(),
            style: TextStyle(
              fontSize: 18,
              color: enabled
                  ? Colors.black
                  : Colors.white.withOpacity(0.5), // 文字颜色
            ),
          ),
        ),
      ),
    );
  }
}